#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import permission
import adebook
import counters

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None

        errMsg = ""
        ebookInfo = {}
        ebidStr = self.request.get('ebid')
        try:
            ebid = int(ebidStr)
        except ValueError:
            ebid = 0
        if ebid != 0:
            adebookModel = adebook.readAdebookById(ebid)
            if not adebookModel:
                errMsg = "没有对应的电子书：ebid=" + str(ebid)
            else:
                ebookInfo = adebookModel

        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'xnuid': xnuid,
            'nav_selected': 'ebook',
            'errMsg': errMsg,
            'ebookInfo': ebookInfo
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/admin/editebookinfo.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        xnuid = cookieDict.get('user')
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        callbackUrl = utils.getUrlPathQuery(self.request)
        if not is_logged_in or not permission.hasResetCounterPermission(xnuid):
            self.redirect("/login?" + urllib.urlencode({'url':callbackUrl}))
            return None

        errMsg = ''
        sourceStr = self.request.get('source')
        try:
            source = int(sourceStr)
        except ValueError:
            source = -1
        title = self.request.get('title')
        author = self.request.get('author')
        descr = self.request.get('descr')
        imgsrc = self.request.get('imgsrc')
        link = self.request.get('link')
        #filtering ebook fields
        filteredMap = adebook.checkAdebook(source, title, author, descr, link, imgsrc)        
        if 'errMsg' in filteredMap:
            errMsg = filteredMap['errMsg']

        if not errMsg:
            ebidStr = self.request.get('ebid')
            try:
                ebid = int(ebidStr)
            except ValueError:
                ebid = 0
            if ebid == 0:
                adebookModel = adebook.Adebook()
                counter = counters.AtomicCounter('adebook')
                adebookModel.ebid = counter.AtomicInc()
                adebookModel.resv1 = ''
                adebookModel.resv2 = ''
            else:
                adebookModel = adebook.readAdebookById(ebid)
            adebookModel.source = filteredMap['source']
            adebookModel.title = filteredMap['title']
            adebookModel.author = filteredMap['author']
            adebookModel.descr = filteredMap['descr']
            adebookModel.link = filteredMap['link']
            adebookModel.imgsrc = filteredMap['imgsrc']
            adebook.writeAdebook(adebookModel)
            self.redirect("/admin/ebookinfo?ebid=" + str(adebookModel.ebid))
            return None
        else:
            template_values = {
                'staticUrl': conf.staticUrl,
                'jsVersion': conf.jsVersion,
                'cssVersion': conf.cssVersion,
                'xnuid': xnuid,
                'errMsg': errMsg,
                'ebookInfo': {}
            }
            path = os.path.join(os.path.dirname(__file__), 'pages/admin/editebookinfo.html')
            self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/admin/editebookinfo', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
